/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servico;

import br.com.foxinline.enums.ProjetoStatus;
import br.com.foxinline.modelo.Projeto;
import br.com.foxinline.modelo.Situacao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
@Stateless
public class SituacaoServico extends ServicoGenerico<Situacao> {

    public SituacaoServico() {
        super(Situacao.class);
    }

    public List<Situacao> getSituacao(Projeto p){
        String sql ="SELECT s FROM Situacao s JOIN s.projeto p WHERE p.id = :projeto order by s.id desc ";
        
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("projeto", p.getId());
        return (List<Situacao>) query.getResultList();
    }
    
    @Deprecated
    public Situacao situacaoAtual(ProjetoStatus projetoStatus) {

        try {
            String sql = " SELECT distinct s FROM Projeto p JOIN p.situacoes s ";

            sql += "WHERE s.id = (select MAX(st.id) from Situacao st JOIN st.projeto pr where pr.id = p.id) ";

            if (projetoStatus != null) {
                sql += "and s.projetoStatus = :situacao ";
            }

            Query query = getEntityManager().createQuery(sql);

            if (projetoStatus != null) {
                query.setParameter("situacao", projetoStatus);
            }

            return (Situacao) query.getSingleResult();

        } catch (NoResultException e) {
            e.printStackTrace();
            return new Situacao();
        } catch (Exception ex){
            ex.printStackTrace();
            return new Situacao();
        }
    }
    
    public Situacao situacaoAtual(Long projeto) {

        try {
            String sql = " SELECT distinct s FROM Projeto p JOIN p.situacoes s ";

            sql += "WHERE s.id = (select MAX(st.id) from Situacao st JOIN st.projeto pr where pr.id = p.id) ";

            if (projeto != null) {
                sql += "and p.id = :projeto ";
            }

            Query query = getEntityManager().createQuery(sql);

            if (projeto != null) {
                query.setParameter("projeto", projeto);
            }

            return (Situacao) query.getSingleResult();

        } catch (NoResultException e) {
            e.printStackTrace();
            return new Situacao();
        } catch (Exception ex){
            ex.printStackTrace();
            return new Situacao();
        }
    }
}
